package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var timeSlice []string
var dataSlice []int

//HandleData 是用来解析数据文件，从中提取x和y轴的数据，发送给main
//也会检测到异常数据，通过chanE发送给main

func HandleData(filename string, chanX chan<- interface{}, chanY chan<- interface{}, chanE chan<- string) error {

	file, err := os.OpenFile(filename, os.O_RDONLY, 0666)
	if err != nil {
		fmt.Printf("open file err :%s\n", err)
		return err
	}

	reader := bufio.NewReader(file)

	for {
		bufString, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Printf("file read string err :%s\n", err)
			return err
		}
		err = handleSingleLine(bufString, chanE)
		if err != nil {
			fmt.Printf("handleSingleLine err :%s\n", err)
			return err
		}
	}
	close(chanE)

	err = sendDataToJson(chanX, chanY)
	if err != nil {
		fmt.Printf("sendDataToJson err :%s\n", err)
	}
	return nil
}

//处理每一个行的信息，提取数据
func handleSingleLine(line string, c chan<- string) error {
	line = strings.Replace(line, "(", " ", -1)
	line = strings.Replace(line, ")", " ", -1)
	s := strings.Split(line, " ")

	if s[3] != "V_L" {
		c <- line
		return nil
	}
	tmp := s[0] + " " + s[1]
	timeSlice = append(timeSlice, tmp)

	i, err := strconv.Atoi(s[4])
	if err != nil {
		fmt.Printf("Atoi err :%s\n", err)
		return err
	}
	dataSlice = append(dataSlice, i)

	return nil
}

func sendDataToJson(chanX chan<- interface{}, chanY chan<- interface{}) error {

	go func() {
		for _, s := range timeSlice {
			chanX <- s
		}
		fmt.Println("chanX will be closed")
		close(chanX)
	}()

	go func() {
		for _, s := range dataSlice {
			chanY <- s
		}
		fmt.Println("chanY will be closed")
		close(chanY)
	}()

	return nil
}
